package com.ngc.mall.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ngc.mall.common.configure.LocalUser;
import com.ngc.mall.common.configure.exception.BusinessException;
import com.ngc.mall.common.configure.response.ResponseCode;
import com.ngc.mall.common.configure.response.ResponseResult;
import com.ngc.mall.domain.UserDomain;
import com.ngc.mall.dto.UserDTO;
import com.ngc.mall.dto.UserFilterDTO;
import com.ngc.mall.dto.UserPasswordDTO;
import com.ngc.mall.param.LoginParam;
import com.ngc.mall.param.ResetPasswordParam;
import com.ngc.mall.param.RolesParam;
import com.ngc.mall.service.IRoleService;
import com.ngc.mall.service.IUserService;
import com.ngc.mall.util.DoubleJWT;
import com.ngc.mall.util.Tokens;
import com.ngc.mall.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

/**
 *  用户
 *
 * @author : Chen Xiao Lin
 * @Date : 2023/3/20 10:11
 **/

@RequestMapping("/user")
@RestController
@Api(tags = "用户（管理端）")
public class UserController {
    @Resource
    private IUserService userService;

    @Resource
    private IRoleService iRoleService;

    @Resource
    private DoubleJWT jwt;

    @GetMapping("/test")
    public void test(){
//        LocalDate date=LocalDate.now();
//        return date.getDayOfMonth();
        String[] GENERATE_SOURCE = new String[]{"0", "1", "2", "3", "4", "5", "6", "7",
                "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z"};
        String i=generateByRandom(8);
        System.out.println(i);
    }
    public static String generateByRandom(final int length) {
        StringBuilder randomSb = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            // 输出字母还是数字
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 字符串
            if ("char".equals(charOrNum)) {
                // 判断字母大小写
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
                randomSb = randomSb.append((char) (choice + random.nextInt(26)));
            } else {
                randomSb = randomSb.append(random.nextInt(10));
            }
        }
        return randomSb.toString();
    }
    @GetMapping("/id/{id}")
    @ApiOperation("根据id用户详情(包含权限)")
    public ResponseResult<UserVO> getDetailById(@PathVariable Long id){
        return ResponseResult.success(userService.getDetailById(id));
    }


    @GetMapping("/list")
    @ApiOperation("查询所有用户")
    public ResponseResult<List<UserDomain>> selectAllUser(){
        return ResponseResult.success(userService.findAll());
    }


    @PostMapping("")
    @ApiOperation("注册用户")
    public ResponseResult<Long> register(@RequestBody UserDomain userDomain){
        return ResponseResult.success(userService.register(userDomain));
    }

    @PutMapping("/self/info")
    @ApiOperation("更新当前登录用户个人信息")
    public ResponseResult<Boolean> updateSelfInfo(@RequestBody UserDTO dto){
        return ResponseResult.auto(userService.updateSelfInfo(dto));
    }

    @PutMapping("self/password")
    @ApiOperation("更新个人登录密码")
    public ResponseResult<Boolean> updateSelfPassword(@RequestBody UserPasswordDTO dto){
        return ResponseResult.auto(userService.updateSelfPassword(dto));
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResponseResult<Tokens> login(@RequestBody LoginParam loginParam){
        UserDomain domain=userService.findUserByAccount(loginParam.getAccount());
        if (domain==null){
            throw new BusinessException(ResponseCode.LOGIN_PASSWORD_ERROR);
        }
        Boolean valid=userService.verifyUsernamePassword(domain.getId(),domain.getAccount(),loginParam.getPassword());
        if(!valid){
            throw new BusinessException(ResponseCode.LOGIN_PASSWORD_ERROR);
        }
        Boolean save=userService.update(Wrappers.<UserDomain>lambdaUpdate().eq(UserDomain::getId,domain.getId()).set(UserDomain::getLoginTime, LocalDateTime.now()));
        if(!save){
            return null;
        }
        return ResponseResult.success(jwt.generateTokens(domain.getId()));
    }

    @PutMapping("/id/resetPassword/{id}")
    @ApiOperation("重置密码")
    public ResponseResult<Boolean> resetPasswordByUserId(@PathVariable Long id, @RequestBody ResetPasswordParam passwordParam){
        return ResponseResult.auto(userService.resetPassword(id,passwordParam.getNewPassword()));
    }


    @GetMapping("/info")
    @ApiOperation("获取登录用户信息")
    public ResponseResult<UserVO> getSelfInfo(){
        return ResponseResult.success(userService.getSelfInfo());
    }

    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public ResponseResult<Boolean> logout(){
        LocalUser.clearLocalUser();
        return ResponseResult.success(true);
    }


//    @PutMapping("/self/info")
//    @ApiOperation("修改登录用户基础信息")
//    public ResponseResult<Boolean> updateAdminInfo(@RequestBody String nickname){
//        UserDomain domain=LocalUser.getLocalUser();
//        return ResponseResult.auto(userService.update(Wrappers.<UserDomain>lambdaUpdate().eq(UserDomain::getId,domain.getId()).set(UserDomain::getNickname,nickname)));
//    }

//    @PutMapping("/self/password")
//    @ApiOperation("修改登录用户密码")
//    public ResponseResult<Boolean> updateLocalUserPassword(@RequestBody PasswordParam param){
//        UserDomain domain=LocalUser.getLocalUser();
//       boolean isSame=EncryptUtil.verify(param.getOriginalPassword(),EncryptUtil.enrypt(domain.getPassword()));
//       if(isSame){
//           return ResponseResult.auto(userService.update(Wrappers.<UserDomain>lambdaUpdate().eq(UserDomain::getId,domain.getId()).set(UserDomain::getPassword,param.getNewPassword())));
//       }else{
//           System.out.println("原始密码错误");
//           return null;
//       }
//    }

    @PutMapping("/id/{id}")
    @ApiOperation("编辑用户信息(不包括分配角色、修改密码）")
    public ResponseResult<Boolean> updateById(@PathVariable Long id,@RequestBody UserDomain domain){
        return ResponseResult.auto(userService.updateById(id,domain));
    }

    @PutMapping("/assign/role/{id}")
    @ApiOperation("为用户分配角色")
    public ResponseResult<Boolean> assignRolesById(@PathVariable Long id, @RequestBody RolesParam param){
        return ResponseResult.auto(userService.assignRolesById(id,param.getRoleIdList()));
    }


    @DeleteMapping("/id/{id}")
    @ApiOperation("根据id删除用户")
    public ResponseResult<Boolean> deleteById(@PathVariable Long id){
        return ResponseResult.success( userService.removeById(id));
    }


    @PutMapping("/id/{id}/enable")
    @ApiOperation("启用用户")
    public ResponseResult<Boolean> updateStatusToEnabled(@PathVariable Long id) {
        return ResponseResult.auto(userService.update(Wrappers.<UserDomain>lambdaUpdate().eq(UserDomain::getId,id).set(UserDomain::getOnline,true)));
    }


    @PutMapping("/id/{id}/disable")
    @ApiOperation("停用用户")
    public ResponseResult<Boolean> updateStatueToDisabled(@PathVariable Long id){
        return ResponseResult.auto(userService.update(Wrappers.<UserDomain>lambdaUpdate().eq(UserDomain::getId,id).set(UserDomain::getOnline,false)));
    }

    @PostMapping("/search")
    @ApiOperation("模糊搜索")
    public ResponseResult<List<UserDomain>> search(@RequestBody UserFilterDTO dto){
        return ResponseResult.success(userService.search(dto));
    }
}
